package org.suze.springboot.elasticsearch.param;

import lombok.Builder;
import lombok.Data;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.Serializable;

import static org.elasticsearch.action.support.IndicesOptions.LENIENT_EXPAND_OPEN;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

/**
 * @description: 查询参数基类
 * @Date : 2020/5/14 上午11:30
 * @Author : 石冬冬-Seig Heil
 */
@Data
@Builder
public class BaseSearchParam implements Serializable {

    private static final long serialVersionUID = 3092443027225940353L;

    /**
     * 查询每次返回的数量
     */
    protected final static int SEARCH_PER_SIZE = 100;

    /**
     * 游标时间
     */
    protected final static long SCROLL_TIME_SECOND = 30L;
    /**
     * 获取索引
     *
     * @return
     */
    protected String[] indices;

    /**
     * 创建SearchSourceBuilder，并设置通用的属性
     *
     * @return
     */
    public SearchSourceBuilder createSearchSourceBuilder() {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(createQueryBuilder());
        searchSourceBuilder.size(SEARCH_PER_SIZE);
        return searchSourceBuilder;
    }

    /**
     * 创建查询条件
     *
     * @return
     */
    public QueryBuilder createQueryBuilder() {
        return matchAllQuery();
    }

    /**
     * 创建游标
     *
     * @return
     */
    public Scroll createScroll() {
        return new Scroll(TimeValue.timeValueSeconds(SCROLL_TIME_SECOND));
    }

    /**
     * 获取请求
     *
     * @return
     */
    public ActionRequest request(){
        SearchRequest searchRequest = new SearchRequest(indices);
        searchRequest.source(createSearchSourceBuilder());
        searchRequest.scroll(createScroll());
        searchRequest.indicesOptions(LENIENT_EXPAND_OPEN);
        return searchRequest;
    }

}
